import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { InfiniteScroll, NavBar } from 'antd-mobile'

import ArticleItem from '@/components/ArticleItem'

import styles from './index.module.scss'
import { useEffect, useRef, useState } from 'react'
import { getSearchResultApi } from '@/api/search'
import { ArticlesItem } from '@/types/data'

const Result = () => {
  const history = useNavigate()
  // 1. 获取路径中query参数
  const location = useLocation()
  // 方式1:
  // 语法：URLSearchParams('?key1=val1&key2=val2')
  // const query = new URLSearchParams(location.search)
  // 方式2：
  const [searchParams] = useSearchParams()
  console.log('获取搜索关键词：', location, searchParams.get('q'))
  // 搜索结果list变量
  const [list, setList] = useState<ArticlesItem[]>([])
  // useEffect(() => {
  //   ;(async () => {
  //     const { data } = await getSearchResultApi({
  //       page: 1,
  //       q: searchParams.get('q'),
  //     })
  //     console.log('搜索结果：', data)
  //     setList(data.results)
  //   })()
  // }, [])

  const [hasMore, setHasMore] = useState(true)
  const page = useRef(1)
  async function loadMore() {
    const {
      data: { results, total_count },
    } = await getSearchResultApi({
      q: searchParams.get('q'),
      page: page.current,
    })
    setList([...list, ...results])
    if (total_count === list.length) {
      setHasMore(false)
    } else {
      page.current++
    }
  }

  const renderArticleList = () => {
    return list.map((item, index) => {
      return (
        <div
          key={index}
          className="article-item"
          onClick={() => history(`/article/${item.art_id}`)}
        >
          <ArticleItem type={item.cover.type} item={item} />
        </div>
      )
    })
  }

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {renderArticleList()}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </div>
    </div>
  )
}

export default Result
